<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="借阅人" prop="borrower">
        <el-input
            v-model="queryParams.borrower"
            placeholder="请输入借阅人"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="被借阅人" prop="borrowerFrom">
        <el-input
            v-model="queryParams.borrowerFrom"
            placeholder="请输入被借阅人"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="档案类型" prop="fileType">
        <el-input
            v-model="queryParams.fileType"
            placeholder="请输入档案类型"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否打印" prop="whetherPrint">
        <el-select v-model="queryParams.whetherPrint" placeholder="请选择是否打印" clearable size="small">
          <el-option
              v-for="dict in whetherPrintOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="借阅状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择借阅状态" clearable size="small">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalStatus">
        <el-input
            v-model="queryParams.approvalStatus"
            placeholder="请输入审批状态"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form v-if="false" label-width="68px">
      <el-form-item label="流程Key" prop="processKey">
        <el-input
          v-model="processKey"
          placeholder="请输入流程Key"
          clearable
          size="small"
          style="width:200px"
        />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['business:fileLoanApplication:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:fileLoanApplication:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:fileLoanApplication:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:fileLoanApplication:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileLoanApplicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="借阅人" align="center" prop="borrowerName"/>
      <el-table-column label="借阅单位" align="center" prop="borrowingUnitName"/>
      <el-table-column label="被借阅人" align="center" prop="borrowerFromName"/>
      <el-table-column label="借阅开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借阅结束时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否打印" align="center" prop="whetherPrint">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_print" :value="scope.row.whetherPrint"/>
        </template>
      </el-table-column>
      <el-table-column label="借阅状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.borrow_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:fileLoanApplication:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:fileLoanApplication:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status==='waiting'"
            size="mini"
            type="text"
            icon="el-icon-back"
            @click="cancelProcessApply(scope.row)"
          >撤销</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status!=='draft'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改借阅申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-tabs type="border-card">
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="借阅人" prop="borrower">
              <user-select v-model="form.borrower" :disabled="isView" placeholder="请选择借阅人" :max-show="1"></user-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借阅单位" prop="borrowingUnit">
              <treeselect v-model="form.borrowingUnit" :disabled="isView" :options="deptOptions" :show-count="true"
                          placeholder="请选择借阅单位"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="被借阅人" prop="borrowerFrom">
              <person-select multiple @change="borrowerFromChange" :disabled="isView" v-model="form.borrowerFrom" placeholder="请选择被借阅人"></person-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="借阅开始时间" prop="startDate">
              <el-date-picker clearable size="small" style="width: 100%" :disabled="isView"
                              v-model="form.startDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择借阅开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借阅结束时间" prop="endDate">
              <el-date-picker clearable size="small" style="width: 100%" :disabled="isView"
                              v-model="form.endDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择借阅结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="档案类型" prop="fileType">
              <el-checkbox-group v-model="selectDocOptions" :disabled="isView" @change="handleCheckedDocChange">
                <el-checkbox v-for="city in docOptions" :label="city.id" :key="city.name">{{city.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否打印">
              <el-radio-group v-model="form.whetherPrint">
                <el-radio :disabled="isView"
                  v-for="dict in whetherPrintOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :disabled="isView" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
          </el-form>
            <div  class="dialog-footer" style="float:right" v-if="flag">
              <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂 存</el-button>
              <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提 交</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId"></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 提交 -->
    <verify ref="verifyRef" @submitCallback="submitCallback" :taskId="taskId" :taskVariables="taskVariables" :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
import {
  addFileLoanApplication,
  delFileLoanApplication,
  exportFileLoanApplication,
  getFileLoanApplication,
  listFileLoanApplication,
  updateFileLoanApplication
} from "@/api/business/fileLoanApplication";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UserSelect from "@/components/UserSelect/index.vue";
import PersonSelect from "@/components/PersonSelect/index.vue";
import processApi from "@/api/workflow/processInst";
import {listDirectory} from "@/api/business/directory";
import verify from "@/components/Process/Verify.vue";
import history from "@/components/Process/History.vue";
import {mapGetters} from "vuex";

export default {
  name: "FileLoanApplication",
  components: {history, verify, UserSelect, PersonSelect, Treeselect},
  computed: {
    ...mapGetters(['userInfo']),
    test: () => 'test'
  },
  dicts: ['is_print', 'borrow_state','act_status'],
  data() {
    return {
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      isView: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 部门树选项
      deptOptions: [],
      //档案类型
      docOptions: [],
      selectDocOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 借阅申请表格数据
      fileLoanApplicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否打印字典
      whetherPrintOptions: [],
      // 借阅状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        borrower: null,
        borrowingUnit: null,
        borrowerFrom: null,
        fileType: null,
        whetherPrint: null,
        status: null,
        approvalStatus: null,
      },
      // processKey: "file_lending",
      // 表单参数
      form: {
        borrower: "1,2"
      },
      // 表单校验
      rules: {
        borrower: [
          {required: true, message: "借阅人不能为空", trigger: "blur"}
        ],
        borrowingUnit: [
          {required: true, message: "借阅单位不能为空", trigger: "blur"}
        ],
        borrowerFrom: [
          {required: true, message: "被借阅人不能为空", trigger: "blur"}
        ],
        startDate: [
          {required: true, message: "借阅开始时间不能为空", trigger: "blur"}
        ],
        endDate: [
          {required: true, message: "借阅结束时间不能为空", trigger: "blur"}
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'BorrowApplication'
    };
  },
  created() {
    this.getList();
    this.getDicts("is_print").then(response => {
      this.whetherPrintOptions = response.data;
    });
    this.getDicts("borrow_state").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    borrowerFromChange(data){
      this.form.borrowerFromName = data.map(item => item.name).join(',');
    },
    handleCheckedDocChange(value) {

      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    /** 查询借阅申请列表 */
    getList() {
      this.loading = true;
      listFileLoanApplication(this.queryParams).then(response => {
        this.fileLoanApplicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否打印字典翻译
    whetherPrintFormat(row, column) {
      return this.selectDictLabel(this.whetherPrintOptions, row.whetherPrint);
    },
    // 借阅状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        borrower: this.userInfo.userId,
        borrowingUnit: this.userInfo.dept.deptId,
        borrowerFrom: null,
        borrowerFromName: null,
        startDate: null,
        endDate: null,
        fileType: null,
        whetherPrint: "0",
        status: null,
        approvalStatus: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true;
      this.isView = false;
      this.reset();
      this.getTreeselect();
      this.getDocOptions();
      this.selectDocOptions = [];
      this.open = true;
      this.title = "添加借阅申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true;
      this.reset();
      this.getTreeselect();
      this.getDocOptions();
      this.selectDocOptions = [];
      const id = row.id || this.ids;
      this.isView = false;
      getFileLoanApplication(id).then(response => {
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        let fileTypeIds = response.data.fileType.split(',');
        for(let i = 0; i < fileTypeIds.length; i++){
          this.selectDocOptions.push(Number(fileTypeIds[i]));
        }
        this.open = true;
        this.title = "修改借阅申请";
        this.sendMessage = {
          title:'借阅申请',
          messageContent:'单据【'+row.id+"】申请"
        }
      });
    },
    //查看
    handleView(row){
      this.flag = false
      this.loading = true;
      this.getTreeselect();
      this.getDocOptions();
      this.selectDocOptions = [];
      this.reset();
      const id = row.id || this.ids;
      this.isView = true;
      getFileLoanApplication(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        let fileTypeIds = response.data.fileType.split(',');
        for(let i = 0; i < fileTypeIds.length; i++){
          this.selectDocOptions.push(Number(fileTypeIds[i]));
        }
        this.open = true;
        this.title = "查看借阅申请";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除借阅申请编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delFileLoanApplication(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有借阅申请数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportFileLoanApplication(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getDocOptions(){
      let data = {'parentId':0};
      listDirectory(data).then(response =>{
        this.docOptions = response.data;
      })
    },
    submitForm(flag) {
      this.form.fileType = this.selectDocOptions.join(',');
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.buttonLoading = true;
          let resData = null;
          if (this.form.id != null) {
            resData = await updateFileLoanApplication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if(flag === 'submit'){
                this.submitFormApply(response.data)
              }
              this.getList();
              return response.data;
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            resData = await addFileLoanApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if(flag === 'submit'){
                this.submitFormApply(response.data)
              }
              this.getList();
              return response.data
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
          // if (flag === 'submit') {
          //   this.submitFormApply(resData)
          // }
        }
      });
    },
    // 提交成功回调
    submitCallback(){
      this.open = false;
      this.getList();
    },
    //提交流程
    submitFormApply(entity) {
      //流程变量
      this.taskVariables = {
        entity: entity,
        userId: '1',
      }
      const data = {
        processKey: this.processKey, // key
        businessKey: entity.id, // 业务id
        variables: this.taskVariables,
        classFullName: 'com.ruoyi.business.domain.FileLoanApplication'
      }
      // 启动流程
      processApi.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        this.$refs.verifyRef.visible = true
        this.$refs.verifyRef.reset()
      })
    },//撤回
    cancelProcessApply(row){
      this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processApi.cancelProcessApply(row.actBusinessStatus.processInstanceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.borrowingUnit = data.id;
      this.getList();
    }
  }
};
</script>
